package com.template.config.websocket;

import com.sun.security.auth.UserPrincipal;
import com.template.common.lang.Const;
import com.template.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * websocket的用户认证拦截器
 */
@Slf4j
public class WebSocketAuthInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request,
                                   @NotNull ServerHttpResponse response,
                                   @NotNull WebSocketHandler wsHandler,
                                   @NotNull Map<String, Object> attributes) {

        ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        String token = req.getServletRequest().getParameter("token");
        if (!JwtUtils.validate(token)) {
            log.warn("failed to connect websocket, token validation failed");
            return false;
        }
        Long userId = JwtUtils.getVal(token);
        if (userId == null) {
            log.warn("failed to connect websocket, token has expired");
            return false;
        }

        attributes.put(Const.Sock.PRINCIPAL, new UserPrincipal(userId.toString()));
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
